/*
 * Project: book
 * 
 * File Created at 2017年9月12日
 * 
 * Copyright 2016 CMCC Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * ZYHY Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license.
 */
package com.whb.book.common.encDec;

/**
 * @Type ByteUtil.java
 * @Desc 
 * @author wanghb
 * @date 2017年9月12日 下午1:17:47
 * @version 
 */
public class ByteUtil {

    private static final String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    /**
     * 
     * byte2hex:(). <br/>
     * 
     * 
     * @author wanghb
     * @param b
     * @return
     * @since JDK 1.8
     */
    public static String byte2hex(byte b)
    {
      int ret = b;

      if (ret < 0) {
        ret += 256;
      }
      int m = ret / 16;
      int n = ret % 16;
      return hexDigits[m] + hexDigits[n];
    }

    /**
     * 
     * bytes2hex:(). <br/>
     * 
     * 
     * @author wanghb
     * @param bytes
     * @return
     * @since JDK 1.8
     */
    public static String bytes2hex(byte[] bytes)
    {
      StringBuffer sb = new StringBuffer();
      for (int i = 0; i < bytes.length; i++) {
        sb.append(byte2hex(bytes[i]));
      }
      return sb.toString();
    }

    /**
     * 
     * hex2bytes:(). <br/>
     * 
     * 
     * @author wanghb
     * @param hexstr
     * @return
     * @since JDK 1.8
     */
    public static byte[] hex2bytes(String hexstr)
    {
      byte[] b = new byte[hexstr.length() / 2];
      int j = 0;
      for (int i = 0; i < b.length; i++) {
        char c0 = hexstr.charAt(j++);
        char c1 = hexstr.charAt(j++);
        b[i] = ((byte)(parse(c0) << 4 | parse(c1)));
      }
      return b;
    }

    /**
     * 
     * parse:(). <br/>
     * 
     * 
     * @author wanghb
     * @param c
     * @return
     * @since JDK 1.8
     */
    private static int parse(char c) {
      if (c >= 'a')
        return c - 'a' + 10 & 0xF;
      if (c >= 'A')
        return c - 'A' + 10 & 0xF;
      return c - '0' & 0xF;
    }

    public static void main(String[] args)
    {
      System.out.println(byte2hex((byte)25));
      System.out.println(bytes2hex(new byte[] { 25, 32 }));
      System.out.println(hex2bytes("0F")[0]);
    }
}


/**
 * Revision history
 * -------------------------------------------------------------------------
 * 
 * Date Author Note
 * -------------------------------------------------------------------------
 * 2017年9月12日 wanghb create
 */